﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MobileSales.Model.Products;
using MobileSales.Website.Properties;
using System.IO;
using MobileSales.Website.ProductService;
using MobileSales.Website.Infrastructure;
using System.ServiceModel;
using MobileSales.Model.Exceptions;
using MobileSales.Common.Logger;
using MobileSales.Website.Infrastructure.Messaging;
using MobileSales.Website.Localization;

namespace MobileSales.Website.Controllers
{
    [Authorize]
    public class ProductImagesController : ControllerBase
    {
        #region Create
        //
        // GET: /ProductImages/Create

        public ActionResult Create(int productId)
        {
            ViewData["productId"] = productId;
            return View();
        }

        //
        // POST: /ProductImages/Create

        [HttpPost]
        public ActionResult Create(HttpPostedFileBase file, int position, int productId)
        {
            try
            {
                String websiteAddr = Settings.Default.WebsiteURL;

                long fileSizeKb = file.ContentLength / 1024;
                if (fileSizeKb > 0 && fileSizeKb <= Settings.Default.MaxUploadSizeKB)
                {
                    string ext = file.FileName.Split('.').Last();
                    var fileName = string.Format("{0}.{1}", Guid.NewGuid().ToString(), ext);
                    var path = Path.Combine(Server.MapPath(Settings.Default.UploadDir), fileName);
                    file.SaveAs(path);
                    string filePath = string.Format("{0}/{1}", Settings.Default.UploadDir.Replace("~/", websiteAddr), fileName);

                    ProductServiceClient client = new ProductServiceClient();
                    client.AddValidationToken(this.Token);

                    ProductImage img = new ProductImage
                    {
                        Path = filePath,
                        Position = position
                    };
                    client.StoreProductImage(productId, img);
                    client.Close();
                    return RedirectToAction("Details", "Products", new { id = productId });
                }
                else
                {
                    throw new Exception("File has incorrect size");
                }
            }
            catch (FaultException<ValidationException> ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ex.Detail.Message, MessageType.Error);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorUploadPhoto, MessageType.Error);

            }
            return View(productId);
        } 
        #endregion

        #region Delete
        //
        // GET: /ProductImages/Create

        public ActionResult Delete(int id, int productId)
        {
            Product product = null;
            try
            {
                ViewData["productId"] = productId;
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);
                product = productService.GetProduct(productId);
                productService.Close();

                ProductImage img = product.Images.Where(x => x.Id.Equals(id)).FirstOrDefault();
                return View(img);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(InfoStrings.ProductNotFound, MessageType.Error);
                return RedirectToAction("Details", "Products", new { id = productId });
            }
        }

        //
        // POST: /Products/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, int productId, FormCollection form)
        {
            try
            {
                ProductService.ProductServiceClient productService = new ProductService.ProductServiceClient();
                productService.AddValidationToken(this.Token);


                Product product = productService.GetProduct(productId);
                if (product == null)
                {
                    productService.Close();
                    throw new Exception("Product not found");
                }

                var fileName = product.Images.Where(x => x.Id.Equals(id)).Select(x => x.Path).FirstOrDefault();
                fileName = fileName.Split('/').Last();
                var path = Path.Combine(Server.MapPath(Settings.Default.UploadDir), fileName);
                System.IO.File.Delete(path);

                productService.DeleteProductImage(id);
                productService.Close();

                this.SetMessage(InfoStrings.ProductImageDeleted, MessageType.Info);
                return RedirectToAction("Details", "Products", new { id = productId });
            }
            catch (FaultException<ValidationException> ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ex.Detail.Message, MessageType.Error);
            }
            catch (Exception ex)
            {
                CLogger.LogDebug(ex);
                this.SetMessage(ErrorStrings.ErrorProductImageDeleting, MessageType.Error);
            }
            return RedirectToAction("Details", "Products", new { id = productId });
        } 
        #endregion
    }


}
